package com.hzdl.util;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author ：Reus CAI
 * @date ：Created in 2020/12/17 14:31
 * @description：创建连接工具类
 * @modified By：
 * @version: $
 */


public class ConnectionUtil {

    // 用本地线程创建连接

    private DataSource dataSource;
    private ThreadLocal<Connection> threadLocal;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public void setThreadLocal(ThreadLocal<Connection> threadLocal) {
        this.threadLocal = threadLocal;
    }

    public Connection getConnection() {
        Connection connection = threadLocal.get();

        try {
            if (connection == null) {
                connection = dataSource.getConnection();
                threadLocal.set(connection);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }


    /*解除threadlock中的connection绑定*/
    public void removeConnection(){

        threadLocal.remove();
    }


}
